package com.bnlr.lrparking.appui.search;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.bnlr.lrparking.appui.stall.StallDealActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.SeachTypeAdapter;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.IntentConstant;
import com.bnlr.lrparking.model.HotSearchBean;
import com.bnlr.lrparking.model.TopSeachModel;
import com.bnlr.lrparking.util.RecordSQLiteOpenHelper;
import com.bnlr.lrparking.widget.popcity.PopupCheckBox;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.HttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Response;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hp on 2017/10/9.
 * 搜索 热搜 历史记录
 */
public class SeachActiity extends BaseActivity {

    List<TopSeachModel> mlist = new ArrayList<>();
    private TagFlowLayout mFlowLayout, mFlowlayout_history;//热搜和历史记录列表
    private LayoutInflater mInflater;
    private PopupCheckBox rely_seach;
    private GridView rv_seach_type;
    private SeachTypeAdapter seachTypeAdapter;
    private String[] strSeachType;
    private TextView tv_colse, hot_text_view;
    private EditText ed_seach;
    private ImageView img_clearaway; // 清除历史记录按钮
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private SQLiteDatabase db;
    private TextView tv_tip;
    private BaseAdapter adapter;
    private String edStr = "";
    private String type = "10"; // 10出租，11出售，20求租，21求购
    private List<String> mHistory;
    private boolean isAllSearch = false;
    private String keyWords = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seach);
        mInflater = LayoutInflater.from(this);
        initComponent();
        initView();
    }

    private void initComponent() {
        strSeachType = new String[]{"车位出租", "车位出售", "车位求租", "车位求购"};
        mFlowlayout_history = (TagFlowLayout) findViewById(R.id.id_flowlayout_history);
        tv_tip = (TextView) findViewById(R.id.tv_tip);
        ed_seach = (EditText) findViewById(R.id.ed_seach);
        ed_seach.setFocusable(true);
        ed_seach.setFocusableInTouchMode(true);
        ed_seach.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        hot_text_view = (TextView) findViewById(R.id.hot_text_view);
        rely_seach = (PopupCheckBox) findViewById(R.id.rely_seach);
        tv_colse = (TextView) findViewById(R.id.tv_colse);
        img_clearaway = (ImageView) findViewById(R.id.img_clearaway);
        tv_colse.setOnClickListener(this);
        img_clearaway.setOnClickListener(this);
    }

    private void initView() {
        Intent intent = getIntent();
        isAllSearch = intent.getBooleanExtra(IntentConstant.IS_ALL_SEARCH, false);
        type = getIntent().getStringExtra("dealType");
        if (TextUtils.isEmpty(type)) {
            type = "10";
        }
        keyWords = intent.getStringExtra(IntentConstant.INTENT_STALL_DEAL_SEARCH);
        if (TextUtils.isEmpty(keyWords)) {
            keyWords = "";
        }
        ed_seach.setText(keyWords);
        ed_seach.setSelection(ed_seach.getText().toString().length());
        if (isAllSearch) {
            rely_seach.setVisibility(View.VISIBLE);
            initPop();
        } else {
            rely_seach.setVisibility(View.GONE);
        }
        setTopSearch();
        // 搜索框的键盘搜索键点击回调
        ed_seach.setOnKeyListener(new View.OnKeyListener() { // 输入完后按键盘上的搜索键

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    // 按完搜索键后将当前查询的关键字保存起来,如果该关键字已经存在就不执行保存
                    boolean hasData = hasData(ed_seach.getText().toString().trim());
                    if (!hasData) {
                        if (!ed_seach.getText().toString().trim().equals("")) {
                            insertData(ed_seach.getText().toString().trim());
                            queryData("");
                        }
                    }

                    handleSearchResult();
                }
                return false;
            }
        });

        // 搜索框的文本变化实时监听
        ed_seach.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                edStr = ed_seach.getText().toString();
                if (s.toString().trim().length() == 0) {
                    tv_tip.setText("搜索历史");
                } else {
                    tv_tip.setText("搜索结果");
                }
                String tempName = ed_seach.getText().toString();
                // 根据tempName去模糊查询数据库中有没有数据
                //queryData(tempName);
            }
        });
        // 第一次进入查询所有的历史记录
        queryData("");
    }

    /**
     * 处理点击事件
     */
    private void handleSearchResult() {
        Intent intent = new Intent();
        intent.putExtra(IntentConstant.INTENT_STALL_DEAL_SEARCH, ed_seach.getText().toString());
        if (isAllSearch) {
            switch (type) {
                case "10":
                case "11":
                    intent.setClass(this, StallDealActivity.class);
                    intent.putExtra("from_search", true);
                    intent.putExtra("spaceowertype", "0");
                    break;
                case "20":
                case "21":
                    intent.setClass(this, RentBuyStallActivity.class);
                    break;
                default:
                    break;
            }
            intent.putExtra("dealType", type);
            startActivity(intent);
        } else {
            setResult(IntentConstant.SEARCH_RESULT_CODE, intent);
        }
        finish();
    }


    //初始化热搜
    private void getTopSearchView(int layout) {

        mFlowLayout = (TagFlowLayout) findViewById(R.id.id_flowlayout);
        mFlowLayout.setMaxSelectCount(1);
        setFlowLayoutAdapter(layout);
        //获取点击的事件
        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                boolean hasData = hasData(mlist.get(position).getKeyWord());
                if (!hasData) {
                    insertData(mlist.get(position).getKeyWord());
                    queryData("");
                }
                ed_seach.setText(mlist.get(position).getKeyWord());
                handleSearchResult();
                return true;
            }
        });
    }

    private void setFlowLayoutAdapter(final int layout) {

        mFlowLayout.setAdapter(new TagAdapter<TopSeachModel>(mlist) {
            @Override
            public View getView(FlowLayout parent, int position, TopSeachModel topSeekBeen) {
                TextView tv = (TextView) mInflater.inflate(layout, mFlowLayout, false);
                tv.setTextSize(12);
                tv.setTextColor(0xff333333);
                tv.setText(topSeekBeen.getKeyWord());
                return tv;
            }
        });
    }

    /**
     * 初始化
     */
    private void initPop() {
        View view = View.inflate(this, R.layout.pop_seach_type, null);
        initPopView(view);
        rely_seach.setPopupView(view, 430);
    }

    private void initPopView(View mView) {
        rv_seach_type = (GridView) mView.findViewById(R.id.rv_seach_type);
        seachTypeAdapter = new SeachTypeAdapter(this, strSeachType);
        rv_seach_type.setAdapter(seachTypeAdapter);
        rv_seach_type.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                seachTypeAdapter.setSelectPosition(position);
                rely_seach.setText(strSeachType[position]);
                rely_seach.hidePopup();
                if (position == 0) {
                    type = "10";
                } else if (position == 1) {
                    type = "11";
                } else if (position == 2) {
                    type = "20";
                } else if (position == 3) {
                    type = "21";
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_colse:
                finish();
                break;
            case R.id.img_clearaway:
                setDelect();
                break;
        }
    }

    //

    /**
     * 插入数据
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }

    /**
     * 模糊查询数据
     */
    private void queryData(String tempName) {
        mHistory = new ArrayList<>();
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
        // 创建adapter适配器对象
        while (cursor.moveToNext()) {

            // int personid = cursor.getInt(0); //获取第一列的值,第一列的索引从0开始
            String name = cursor.getString(1);//获取第二列的值
            //int age = cursor.getInt(2);//获取第三列的值
            mHistory.add(name);
        }
        adapter = new SimpleCursorAdapter(this, R.layout.item_topseach, cursor, new String[]{"name"},
                new int[]{R.id.tv_item_seachis}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 设置适配器
        mFlowlayout_history.setAdapter(new TagAdapter<String>(mHistory) {
            @Override
            public View getView(FlowLayout parent, int position, String topSeekBeen) {
                TextView tv = (TextView) mInflater.inflate(R.layout.item_topseach, mFlowlayout_history, false);
                tv.setTextSize(12);
                tv.setTextColor(0xff333333);
                tv.setText(topSeekBeen);
                return tv;
            }
        });

        //获取点击的事件
        mFlowlayout_history.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                ed_seach.setText(mHistory.get(position));
                handleSearchResult();
                return true;
            }
        });

    }

    /**
     * 检查数据库中是否已经有该条记录
     */
    private boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据
     */
    private void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

    //获取热搜json文件
    private void setTopSearch() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.URL_GET_HOT_SEARCH_JSON, LrConstant.GET);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new HttpListener<String>() {
                        @Override
                        public void onSucceed(int what, Response<String> response) {
                            String json = response.get();
                            ArrayList<TopSeachModel> jsonBean = parseData(json);
                            mlist = new ArrayList<>();
                            for (int i = 0; i < jsonBean.size(); i++) {
                                mlist.add(jsonBean.get(i));
                            }
                            getTopSearchView(R.layout.item_topseach);
                        }

                        @Override
                        public void onFailed(int what, Response<String> response) {

                        }
                    }, true);
        } catch (Exception e) {
        }
    }


    private ArrayList<TopSeachModel> parseData(String json) {
        ArrayList<TopSeachModel> result = new ArrayList<>();
        try {
            Gson gson = new Gson();
            String city = AppConfig.getInstance().getString("strCity", "郑州市");
            List<HotSearchBean> list = gson.fromJson(json, new TypeToken<List<HotSearchBean>>() {
            }.getType());
            boolean isHave = false;
            for (int i = 0; i < list.size(); i++) {
                HotSearchBean hot = list.get(i);
                String cityName = hot.getCityName();
                if (cityName.contains(city)) {
                    if (hot.getData().size() > 0) {
                        isHave = true;
                    }
                    for (int j = 0; j < hot.getData().size(); j++) {
                        result.add(new TopSeachModel(hot.getData().get(j).getKeyWord()));
                    }
                    break;
                }
            }
            if (!isHave) {
                hot_text_view.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public void setDelect() {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.title("提示")
                .titleTextColor(getResources().getColor(R.color.black_color))
                .titleTextSize(15)
                .content("确定删除全部历史记录吗？")
                .contentTextSize(15)
                .contentTextColor(getResources().getColor(R.color.gray_color))
                .btnText("取消", "确定")
                .btnNum(2)
                .style(NormalDialog.STYLE_TWO)
                .btnTextColor(getResources().getColor(R.color.gray_color), getResources().getColor(R.color.colorAccent))
                .btnTextSize(15, 15)
                .widthScale(0.8f)//
                .showAnim(new BounceTopEnter())//
                .dismissAnim(new SlideBottomExit())//
                .cornerRadius(7)
                .show();
        dialog.setCancelable(true);
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        deleteData();
                        queryData("");
                    }
                });
    }
}
